#!/usr/bin/env python
# coding=utf-8
##########################################################################
# File Name: ffm.py
# Author: wangdj
# mail: wangdajunttf@163.com
# Created Time: Thu 28 Oct 2021 04:27:56 PM CST
##########################################################################

from time import gmtime
from time import strftime
import copy
import json
import os
import sys
import time
import re
from subprocess import Popen, PIPE, STDOUT, run
from rich import print, print_json
from rich.console import Console
console = Console()

# print sys.argv


# 执行 ffmpeg 命令不会卡住，实时输出
def run_shell(shell):
  print(':vampire:[bold magenta]$[/bold magenta]', shell)
  cmd = Popen(shell,
              stdin=PIPE,
              stderr=sys.stderr,
              close_fds=True,
              stdout=sys.stdout,
              universal_newlines=True,
              shell=True,
              bufsize=1)
  cmd.communicate()
  return cmd.returncode


# if __name__ == '__main__':
#  print(run_shell("ping www.baidu.com"))
# sys.exit()


# 执行 ffmpeg 命令会卡住不实时输出
def exe_command(command):
  """
执行 shell 命令并实时打印输出
:param command: shell 命令
:return: process, exitcode
"""
  print(command)
  process = Popen(command,
                  stdout=PIPE,
                  stderr=STDOUT,
                  shell=True,
                  encoding="utf-8")
  with process.stdout:
    for line in process.stdout.readlines():
      print(line)
  exitcode = process.wait()
  return process, exitcode


# 执行 要等待的 命令会卡住不实时输出，可以拿到输出结果
def cmd(command):
  subp = Popen(command,
               shell=True,
               stdout=PIPE,
               stderr=PIPE,
               encoding="utf-8")
  subp.wait(5)
  if subp.poll() == 0:
    return subp.stdout.readlines()
  else:
    print('失败')


# 位置参数判断
argv = sys.argv
argvLen = len(argv)
if argvLen > 3 or argvLen < 2:
  print(f"argv: {argv} 错误，位置参数应该是：【json 文件名 , 图片间隔秒数】")
  sys.exit()
dataF = sys.argv[1]
# dataF = 'test'
if argvLen == 2:
  interval = 10
elif argvLen == 3:
  interval = sys.argv[2]

thisPath = os.path.split(os.path.realpath(__file__))[0]
jsonDataF = f'{thisPath}/json_data/{dataF}.json'
with open(jsonDataF, 'r', encoding='utf8') as f:
  fsJson = json.load(f)
print(fsJson)
# sys.exit()

gdP = fsJson['gdP']
# dirname = re.findall(r'[^/]+$', gdP)
dirname = re.sub(r'^.+?:/?', '', gdP)
if not dirname:
  print(f'{gdP}')
  sys.exit()
imgUploadGd = f'ttfa:ffmpegImg/{dirname}'
# print(dirname)
# sys.exit()

# rcloneCmd = f"rclone lsf {gdP} |grep '.mp4$'| egrep -v 'S01EP01|S01EP02'"
# rcloneCmd = f"rclone lsf {gdP} | grep '.mkv$'"
# sourceFiles = cmd(rcloneCmd)
localGdP = '/gddown_video'
localImgPath = '/gdup_image'
videoFs = fsJson['videoFs']
# 两个变量会指向同一个数据，第次删除 newVideoFs 第一个，会导致videoFs遍历少一次，现象是只会遍历到第奇数个（第 1.3.5...）。用 deepcopy 可以解决
newVideoFs = copy.deepcopy(videoFs)
for fn in videoFs:
  # fn = f.strip()
  run_shell(f"rclone sync -v '{gdP}/{fn}' {localGdP}")

  localImgP = f'{localImgPath}/{fn}'
  run_shell(f"mkdir -pv '{localImgP}'")

  ffmpegReturnCode = run_shell(
      f"ffmpeg -i '{localGdP}/{fn}' -n -vf fps=1/{interval} -lossless 0 '{localImgP}'/%d.jpg"
  )
  if ffmpegReturnCode != 0:
    print('ffmpeg 生成图片出错！退出脚本！')
    break

  # 图片文件名，格式化处理下
  for imgF in os.listdir(localImgP):
    secSuffix = re.findall(r'^(\d+)(.+)', imgF)[0]
    sec = (int(secSuffix[0]) - 1) * interval
    sfx = secSuffix[1]
    strfT = strftime("%H:%M:%S", gmtime(sec))
    os.system(f'mv {localImgP}/{imgF} {localImgP}/{strfT}{sfx}')

  # 上传图片
  imgUploadGdP = f'{imgUploadGd}/{fn}'
  uploadReturnCode = run_shell(
      f"rclone sync -v '{localImgP}' '{imgUploadGdP}'")
  if uploadReturnCode == 0:
    print('清除临时文件')
    run_shell(f"rm -rvf '{localGdP}/{fn}' '{localImgP}' &")
    print('清除这个文件的 json 数据')
    del(newVideoFs[0])
    newFsJson = {'videoFs': newVideoFs, "gdP": gdP}
    with open(jsonDataF, 'w', encoding='utf8') as f:
      json.dump(newFsJson, f, indent=2, ensure_ascii=False)
  else:
    print('前面的命令出错啦，退出脚本！')
    break
